#include "../../muduo/channel.hpp"
#include "../../muduo/socket.hpp"
#include "../../muduo/log.hpp"
void HandlerClose(Muduo::Channel * channel)
{
    ILOG("close:%d",channel->Fd());
    channel->Remove();//移除监控
    delete channel;
}

void HandlerRead(Muduo::Channel * channel)
{
    int fd = channel->Fd();
    char buf[1024] = {0};
    int ret = recv(fd,buf,1023,0);
    if(ret<=0)
    {
        return HandlerClose(channel);//关闭释放
    }
    channel->EnableWrite();//启动可写事件
    ILOG("%s",buf);
}

void HandlerWrite(Muduo::Channel * channel)
{
    int fd = channel->Fd();
    const char * data = "你好啊!";
    int ret = send(fd,data,strlen(data),0);
    if(ret<0)
    {
        return HandlerClose(channel);//关闭释放
    }
    channel->DisableWrite();//关闭写监控
}

void HandlerError(Muduo::Channel * channel)
{
    return HandlerClose(channel);
}
void HandlerEvent(Muduo::EventLoop * loop,uint64_t timerid)
{
    loop->TimerRefresh(timerid);
}

void Accepter(Muduo::EventLoop * loop,Muduo::Channel * lst_channel)
{
    int fd = lst_channel->Fd();
    int newfd = accept(fd,nullptr,nullptr);
    if(newfd<0) return;
    uint64_t timerid = rand()%10000;
    Muduo::Channel * channel = new Muduo::Channel(loop,newfd);
    channel->SetReadCallback(std::bind(HandlerRead,channel));
    channel->SetWriteCallback(std::bind(HandlerWrite,channel));
    channel->SetCloseCallback(std::bind(HandlerClose,channel));
    channel->SetErrorCallback(std::bind(HandlerError,channel));
    channel->SetEventCallback(std::bind(HandlerEvent,loop,timerid));
    //10s后关闭连接->定时销毁任务,必须在启动读事件之前
    loop->TimerAdd(timerid,10,std::bind(HandlerClose,channel));//非活跃连接的超时释放操作
    channel->EnableRead();
}

int main()
{
    srand(time(nullptr));
    Muduo::EventLoop loop;
    Muduo::Socket lst_sock;
    lst_sock.CreateServer(8080);
    Muduo::Channel channel(&loop,lst_sock.Fd());
    channel.SetReadCallback(std::bind(Accepter,&loop,&channel));
    channel.EnableRead();
    while(true)
    {
        loop.Start();
    }
    lst_sock.Close();
    return 0;
}
